<template>
  <div class="hot-products-page">
    <header-nav />
    
    <!-- Banner区域 -->
    <div class="banner">
      <h1>热门推荐</h1>
      <p>这里汇集了最受欢迎的毛绒玩具!</p>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
      <!-- 左侧筛选器 -->
      <div class="filter-sidebar">
        <div class="filter-header">
          <el-icon><Filter /></el-icon>
          <span>筛选器</span>
        </div>
        
        <el-divider />
        
        <div class="filter-section">
          <h3>价格区间</h3>
          <el-form :model="filterForm">
            <el-form-item>
              <el-slider
                v-model="filterForm.priceRange"
                range
                :min="0"
                :max="1000"
                :marks="{
                  0: '¥0',
                  250: '¥250',
                  500: '¥500',
                  750: '¥750',
                  1000: '¥1000'
                }"
                @change="handlePriceChange"
              />
            </el-form-item>
          </el-form>
        </div>
        
        <el-divider />
        
        <div class="filter-section">
          <h3>分类</h3>
          <el-checkbox-group v-model="filterForm.categories">
            <el-checkbox label="stuffed">毛绒玩具</el-checkbox>
            <el-checkbox label="animals">动物系列</el-checkbox>
            <el-checkbox label="dolls">玩偶系列</el-checkbox>
            <el-checkbox label="accessories">配件</el-checkbox>
          </el-checkbox-group>
        </div>
      </div>

      <!-- 右侧商品展示 -->
      <div class="products-container">
        <!-- 排序和统计 -->
        <div class="products-header">
          <div class="products-count">
            {{ total }} 个商品
          </div>
          <div class="sort-options">
            <el-radio-group v-model="filterForm.sort" size="small">
              <el-radio-button label="rating">好评优先</el-radio-button>
              <el-radio-button label="sales">销量优先</el-radio-button>
              <el-radio-button label="price_asc">价格从低到高</el-radio-button>
              <el-radio-button label="price_desc">价格从高到低</el-radio-button>
            </el-radio-group>
          </div>
        </div>

        <!-- 商品列表 -->
        <div v-if="loading" class="loading">
          <el-skeleton :count="8" animated>
            <template #template>
              <el-card class="product-skeleton">
                <template #default>
                  <el-skeleton-item variant="image" style="width: 100%; height: 200px" />
                  <div style="padding: 14px">
                    <el-skeleton-item variant="h3" style="width: 50%" />
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 8px">
                      <el-skeleton-item variant="text" style="width: 30%" />
                      <el-skeleton-item variant="text" style="width: 20%" />
                    </div>
                  </div>
                </template>
              </el-card>
            </template>
          </el-skeleton>
        </div>
        <div v-else class="products-grid">
          <product-card 
            v-for="product in products" 
            :key="product.id"
            :product="product"
          />
        </div>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[12, 24, 36, 48]"
            :total="total"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import HeaderNav from '../components/HeaderNav.vue'
import ProductCard from '../components/ProductCard.vue'
import { Filter } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from '../utils/axios'

// 从环境变量或默认值获取基础 URL
const baseURL = import.meta.env.VITE_API_URL || 'http://localhost:5000'

const products = ref([])
const loading = ref(true)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(12)

const filterForm = reactive({
  priceRange: [0, 1000],
  categories: [],
  sort: 'rating'
})

const fetchProducts = async () => {
  try {
    loading.value = true;
    
    // 构建查询参数
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      minPrice: filterForm.priceRange[0],
      maxPrice: filterForm.priceRange[1],
      categories: filterForm.categories.join(','),
      sort: filterForm.sort
    };
    
    console.log('Fetching hot products with params:', params);
    
    const response = await axios.get('/api/products/hot', { params });
    
    console.log('Hot products response:', response.data);
    
    // 检查响应格式并正确处理
    if (response.data.success) {
      // 使用 response.data.data 而不是 response.data
      products.value = response.data.data.map(product => ({
        ...product,
        image: product.image ? formatImageUrl(product.image) : ''
      }));
      
      total.value = response.data.total || response.data.data.length;
    } else {
      ElMessage.error(response.data.message || '获取产品失败');
      products.value = [];
    }
  } catch (error) {
    console.error('Error fetching hot products:', error);
    ElMessage.error('获取热门产品失败');
    products.value = [];
  } finally {
    loading.value = false;
  }
};

const handlePriceChange = () => {
  currentPage.value = 1
  fetchProducts()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchProducts()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchProducts()
}

// 添加一个辅助函数来正确格式化图片URL
const formatImageUrl = (imageUrl) => {
  if (!imageUrl) return '';
  
  // 如果已经是完整URL，直接返回
  if (imageUrl.startsWith('http')) return imageUrl;
  
  // 如果已经包含 /uploads/ 前缀，则直接添加基础URL
  if (imageUrl.startsWith('/uploads/')) {
    return `${baseURL}${imageUrl}`;
  }
  
  // 否则添加 /uploads/ 前缀
  return `${baseURL}/uploads/${imageUrl}`;
};

onMounted(() => {
  fetchProducts()
})
</script>

<style scoped>
.hot-products-page {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.banner {
  background: linear-gradient(rgba(0,0,0,0.3), rgba(0,0,0,0.3)), url('/images/hot-bg.jpg');
  /* background: linear-gradient( #e6d7d7 0%, #ecc7c7 100%),url('/images/banner-bg.png'); */
  color: white;
  text-align: center;
  padding: 100px 20px 60px;
  margin-bottom: 40px;
  background-size: cover;
  background-position: center;
}

.banner h1 {
  font-size: 36px;
  margin: 0 0 20px;
}

.banner p {
  font-size: 18px;
  opacity: 0.9;
  margin: 0;
}

.main-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 20px;
  display: grid;
  grid-template-columns: 280px 1fr;
  gap: 40px;
}

.filter-sidebar {
  background: white;
  padding: 20px;
  border-radius: 8px;
  position: sticky;
  top: 20px;
  height: fit-content;
}

.filter-header {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 16px;
  font-weight: bold;
}

.filter-section {
  margin: 20px 0;
}

.filter-section h3 {
  margin: 0 0 15px;
  font-size: 14px;
  color: #666;
}

.products-container {
  background: white;
  padding: 20px;
  border-radius: 8px;
}

.products-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.products-count {
  font-size: 14px;
  color: #666;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  margin-bottom: 40px;
}

.pagination {
  display: flex;
  justify-content: center;
}

@media (min-width: 1600px) {
  .products-grid {
    grid-template-columns: repeat(4, 1fr);
  }
}

@media (max-width: 1200px) {
  .products-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .main-content {
    grid-template-columns: 1fr;
  }
  
  .filter-sidebar {
    position: static;
  }
  
  .products-grid {
    grid-template-columns: repeat(1, 1fr);
  }
}
</style> 